; (function (undefined) {
  "use strict"
  let _global;
  let npmEnv = process.env.NODE_ENV || 'production';//development or production
  localStorage.setItem('npmEnv', npmEnv)
  const DEV = 'https://testimg.iblocke.cn/';//dev env
  const PROD = 'https://img.iblocke.com/';//prod env
  const domain = npmEnv == 'development' ? DEV : PROD;
  const payways = {
    1: "微信",
    2: "GXS",
    3: "ETH",
    4: "BTC"
  }
  const paystatus = {
    0: '未支付',
    1: '已支付'
  }


  try {
    /**axios 拦截器 START */
    axios.defaults.headers.common = {
      'X-Requested-With': 'XMLHttpRequest',
    };
    axios.defaults.headers['cookiekey'] = getKey('cookiekey');
  } catch (err) {
    console.log('axios fail:', err)
  }

  axios.interceptors.request.use(function (request) {
    //show loading 
    let cookiekey = getKey('cookiekey');//兼容方式[wx|gxb]获取cookiekey
    if (cookiekey) {
      startLoading()
    }
    return request;
  })

  axios.interceptors.response.use(function (response) {
    //hide loading 
    if (response) {
      stopLoading()
    }
    return response;// 正常返回每个请求所返回的数据
  }, function (error) {
    return Promise.reject(error)
  });
  /**axios 拦截器 END */

  function startLoading() {
    //cover div
    var div = document.getElementById("wc_loading_div");
    if (div) {
      div.style.display = "block"
      return;
    }
    div = document.createElement('div');
    div.setAttribute("id", "wc_loading_div");
    div.style.position = "fixed";
    div.style.zIndex = "99999";
    div.style.left = "0";
    div.style.top = "0";
    div.style.width = "100%";
    div.style.height = "100vh";
    div.style.background = "rgba(0,0,0,.1)"

    //loading img
    var img = document.getElementById("wc_loading_img") || new Image();
    img.src = '../img/else/loading.svg?ver=1.0.0';
    img.id = 'wc_loading_img';
    img.style.position = "absolute";
    img.style.left = "50%";
    img.style.marginLeft = "-25px";
    img.style.top = "50%";
    img.style.marginTop = "-60px";
    img.style.width = "50px";
    img.style.height = "50px";


    try {
      document.body.appendChild(div);
      div.appendChild(img);
      stopLoading(15000);//15s后自动隐藏
    } catch (err) {
      console.log('appendChild err : loading=>', err)
    }
  }

  function stopLoading(ms = 100) {
    setTimeout(function () {
      document.getElementById("wc_loading_div").style.display = "none";
    }, ms)
  }

  /**获取URL参数 */
  function getUrlParams(param) {
    let reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)");
    let local = window.location;
    let r = local.search.substr(1).match(reg);
    if (r != null)
      return decodeURI(r[2]);//对encodeURI编码处理过的uri进行解码
    return null;
  }

  /**读取cookies  */
  function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
      return unescape(arr[2]);
    else
      return null;
  }

  /**写cookies expires->days */
  function setCookie(name, value, expires = 6) {
    var exp = new Date();
    exp.setTime(exp.getTime() + expires * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
  }

  /**清除cookie */
  function delCookie(key) {
    var date = new Date();
    date.setTime(date.getTime() - 1);
    var delValue = getCookie(key);
    if (!!delValue) {
      document.cookie = key + '=' + delValue + ';expires=' + date.toGMTString();
    }
  }

  /**清除所有cookie */
  function clearAllCookie() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
      for (var i = keys.length; i--;)
        document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
    }
  }

  /**判断是否在微信内部运行 */
  function isWeixin() {
    const ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      return true;
    } else {
      return false;
    }
  }

  /**判断是否在公信宝内部运行 */
  function isGxbao() {
    let isGxbUa = getUrlParams('ua')
    let localIsGxbUa = localStorage.getItem('inGxb_os') || null;
    if (isGxbUa == 'blockcity') {
      localStorage.setItem('inGxb_os', 'blockcity');
      return true;
    } else if (localIsGxbUa) {
      return true;
    }
    return false;
  }

  /**
   * 获取localstorage;
   * 若 key='cookiekey' 则需要判断实效性; 
   * 其他如 key='bountyHunter_id' 则无需判断
   */
  function getLocStore(key) {
    let currUnix = new Date().getTime();//now
    let expires = 6 * 24 * 3600 * 1000; //after six days
    let cookiestartunix = localStorage.getItem(key + "_expires")
    if (key == 'cookiekey') {
      if (!cookiestartunix || cookiestartunix == 'undefined' || currUnix - cookiestartunix > expires) {
        localStorage.removeItem(key)
        localStorage.removeItem(key + "_expires")
        //cookiekey过期或不存在
        return null;
      }
    }
    let cookieVal = localStorage.getItem(key)
    if (cookieVal)
      return cookieVal
    else
      return null;
  }

  /**从cookie或localstorage中获取key值 */
  function getKey(key) {
    let fromCookie = getCookie(key);
    let fromStorage = getLocStore(key);
    return fromCookie || fromStorage
  }

  function unix2Date(format, startdate) {
    let date = startdate ? new Date(startdate * 1) : new Date();
    let y = date.getFullYear();
    let m = fixNum(date.getMonth() + 1);
    let d = fixNum(date.getDate());
    let hh = fixNum(date.getHours());
    let mm = fixNum(date.getMinutes());
    let ss = fixNum(date.getSeconds());
    let dt = format.replace("Y", y).replace("M", m).replace("D", d).replace("hh", hh).replace("mm", mm).replace("ss", ss);
    return dt;
  }

  function date2Unix(date) {
    let fixdate = date.indexOf('-') > 0 ? date.replace(/-/g, '/') : date;
    fixdate = new Date(fixdate)
    return fixdate.getTime();
  }

  function fixNum(num) {
    return num < 10 ? `0${num}` : num
  }
  /**
  * [getLastTime 根据传入日期返回距离当前的时间]
  * @param  {[type]} passedDT [过去的时间日期]
  * @param  {[type]} currDT   [当前或者传入的时间日期]
  * @return {[type]}          [相差的时间 'x天x月x日x时x分x秒']
  */
  function getLastTime(passedDT, currDT) {
    let date1, date2;
    if (passedDT) {
      passedDT = passedDT.indexOf('-') > 0 ? passedDT.replace(/-/g, '/') : passedDT;
      date1 = new Date(passedDT);
    } else {
      date1 = new Date();
    }
    if (currDT) {
      currDT = currDT.indexOf('-') > 0 ? currDT.replace(/-/g, '/') : currDT;
      date2 = new Date(currDT);
    } else {
      date2 = new Date();
    }
    var s1 = date1.getTime(), s2 = date2.getTime();
    var total = (s2 - s1) / 1000;

    var day = parseInt(total / (24 * 60 * 60));//计算整数天数
    var afterDay = total - day * 24 * 60 * 60;//取得算出天数后剩余的秒数
    var hour = parseInt(afterDay / (60 * 60));//计算整数小时数
    var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60;//取得算出小时数后剩余的秒数
    var min = parseInt(afterHour / 60);//计算整数分
    var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60;//取得算出分后剩余的秒数
    var sec = parseInt(afterMin);//计算整数秒
    var strTime = day + "天" + hour + "时" + min + "分" + sec + "秒";
    return strTime;
  }

  function urlAddParams(url, name, value) {
    let valKey = `${name}=${value}`
    let newUrl = url.indexOf('?') > 0 ? `${url}&${valKey}` : `${url}?${valKey}`
    return newUrl;
  }


  /** 批量设置/重写URL参数 */
  function setUrlQuery(params) {
    let querys = '';
    let paramKeys = Object.keys(params);
    paramKeys.map((key, index) => {
      if (index == 0) {
        querys += `?${key}=${params[key]}`;
      } else {
        querys += `&${key}=${params[key]}`;
      }
    })
    let baseurl = window.location.href.split("?")[0];
    let newfullurl = baseurl + querys;
    return newfullurl;
  }

  /** 单个设置URL参数值 */
  function setUrlParam(key, value) {
    var oUrl = window.location.href.toString();
    var rUrl = eval('/(' + key + '=)([^&]*)/gi');
    var nUrl = oUrl.replace(rUrl, key + '=' + value);
    return nUrl;
  }


  /**判断页面运行平台 */
  function osCheck() {
    //wx check
    let isWx = isWeixin();
    let isGxb = isGxbao();
    if (isWx) {
      return 'wx'
    }
    if (isGxb) {
      return 'gxb'
    }
    return null
  }

  /**隐藏站长统计 a 标签 */
  function hideStatisticsA() {
    let aDom = document.getElementsByTagName('a')
    let aLen = aDom.length;
    let filterText = '站长统计';
    if (aLen > 0) {
      if (aDom[aLen - 1].title == filterText) {
        aDom[aLen - 1].style.display = "none";
        return;
      } else {
        aDom.map(item => {
          if (item.title == filterText) {
            item.style.display = "none";
          }
        })
      }
    }
  }


  function Util() { }
  Util.prototype.domain = domain
  Util.prototype.payways = payways
  Util.prototype.paystatus = paystatus
  Util.prototype.getCookie = getCookie
  Util.prototype.setCookie = setCookie
  Util.prototype.isWeixin = isWeixin
  Util.prototype.isGxbao = isGxbao
  Util.prototype.getUrlParams = getUrlParams
  Util.prototype.getLocStore = getLocStore
  Util.prototype.getKey = getKey
  Util.prototype.unix2Date = unix2Date
  Util.prototype.getLastTime = getLastTime
  Util.prototype.fixNum = fixNum
  Util.prototype.urlAddParams = urlAddParams
  Util.prototype.delCookie = delCookie
  Util.prototype.clearAllCookie = clearAllCookie
  Util.prototype.osCheck = osCheck
  Util.prototype.hideStatisticsA = hideStatisticsA
  Util.prototype.setUrlQuery = setUrlQuery
  Util.prototype.setUrlParam = setUrlParam
  Util.prototype.startLoading = startLoading;//生成loading 
  Util.prototype.stopLoading = stopLoading;//结束loading 



  let cookiekey = getKey('cookiekey');
  axios.defaults.headers['cookiekey'] = cookiekey || '';


  _global = (function () { return this || (0, eval)('this'); }());
  if (typeof module !== "undefined" && module.exports) {
    module.exports = Util;
  }
  if (typeof define === "function" && define.amd) {
    define(function () { return Util; });
  }
  !('Util' in _global) && (_global.Util = Util);
}());
